<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container >
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="资金申请单号" :labelCol="{span:4}" :wrapperCol="{span:20}"
                               prop="fundingApplicationNum">
              <a-input disabled v-model="model.fundingApplicationNum" placeholder="请输入资金申请单号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="审批流程" :labelCol="{span:4}" :wrapperCol="{span:20}" prop="approvalProcess">
              <j-dict-select-tag
                type="list"
                :disabled="formDisabled"
                v-model="model.approvalProcess"
                dictCode="funding_application"
                placeholder="请选择审批流程"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="采购订单号" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="procurementCode">
              <a-input-search
                v-model="model.procurementCode"
                placeholder="请选择订购单"
                readonly
                enter-button
                @search="handleSelectOrder"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.procurementCode" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <select-order-list-modal ref="selectOrderModal" @selectFinished="selectOKOrder" />
          <a-col :span="6">
            <a-form-model-item label="单据类型" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="documentType">
              <j-dict-select-tag
                v-model="model.documentType"
                dictCode="cg_document_type"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="供应商名称" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="vendorName">
              <j-popup @input="handleCallBack" v-model="model.vendorName" placeholder="请输入供应商名称" code="supplier_main_info" field="vendorName,supplierId" org-fields="supplier_name,id" dest-fields="vendorName,supplierId"></j-popup>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="采购企业" :labelCol="{span:8}" :wrapperCol="{span:16}"
                               prop="procurementEnterprises">
              <a-input v-model="model.procurementEnterprises" placeholder="请输入采购企业"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="申请金额" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="applicantAmount">
              <a-input-number v-model="model.applicantAmount"   @change="handleAmountChange"placeholder="请输入申请金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="币种" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="currency">
              <j-dict-select-tag
                type="list"
                :disabled="formDisabled"
                v-model="model.currency"
                dictCode="currency"
                placeholder="请选择币种"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="申请人"
              :labelCol="{span:8}"
              :wrapperCol="{span:16}"
              prop="applicant"
            >
              <a-input-search
                v-model="model.applyUserName"
                placeholder="请输入申请人"
                readonly
                enter-button
                @search="handleSelectUser1"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.applicant" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <Tsl-Select-User-Single ref="selectUserModal1" @selectFinished="selectOK"></Tsl-Select-User-Single>
          <a-col :span="6">
            <a-form-model-item label="申请日期" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="applicantDate">
              <j-date placeholder="请选择申请日期" v-model="model.applicantDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="资金类别" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="fundingCategory">
              <j-dict-select-tag
                type="list"
                :disabled="formDisabled"
                v-model="model.fundingCategory"
                dictCode="funding_category"
                placeholder="请选择资金类别"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="账面余额" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="bookBalance">
              <a-input-number v-model="model.bookBalance" placeholder="请输入账面余额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="财务查询人" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="financialInquirer">
              <a-input-search
                v-model="model.financeUserName"
                placeholder="请输入财务查询人"
                readonly
                enter-button
                @search="handleSelectFinanceUser1"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.financialInquirer" hidden></a-input>
            </a-form-model-item>
          </a-col>
          <Tsl-Select-Finance-User ref="selectUserModal2"
                                   @selectFinished="selectFinanceUserOK"></Tsl-Select-Finance-User>
          <a-col :span="6">
            <a-form-model-item label="查询日期" :labelCol="{span:8}" :wrapperCol="{span:16}" prop="queryDate">
              <j-date placeholder="请选择查询日期" v-model="model.queryDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="批准金额" :labelCol="{span:2}" :wrapperCol="{span:22}" prop="approveAmount">
              <a-input-number v-model="model.approveAmount" placeholder="请输入批准金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>

          <a-col :span="23" style="margin-left: 40px">
            <a-tabs v-model="activeKey" @change="handleChangeTabs">
              <a-tab-pane tab="" :key="refKeys[0]" :forceRender="true">
                <a-row :gutter="24" style="margin-bottom: 10px;">
                  <a-col :span="24">
                    <a-button @click="addProducts" icon="plus">新增</a-button>
                  </a-col>
                </a-row>
                <j-vxe-table
                  keep-source
                  :ref="refKeys[0]"
                  :loading="procurementContractReviewTable.loading"
                  :columns="updatedColumns"
                  :dataSource="procurementContractReviewTable.dataSource"
                  :maxHeight="300"
                  :rowNumber="true"
                  :rowSelection="true"
                  :toolbar="true"
                  :toolbarConfig="{ slot: ['prefix', 'suffix'], btn: ['remove', 'clearSelection'] }"
                >
                  <template #action="props">
                    <a-popconfirm title="确定删除吗？" @confirm="handleDeleteRow(props)">
                      <a>删除</a>
                    </a-popconfirm>
                    <a-button type="link" @click="viewContract(props.row)">查看合同</a-button> <!-- 确保没有 disabled 属性 -->
                  </template>
                </j-vxe-table>
              </a-tab-pane>
            </a-tabs>
            <select-procurement-modal ref="selectModal" :supplierName="this.model.vendorName" @orderOk="selProductsOk" />
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="金额大写" :labelCol="{span:2}" :wrapperCol="{span:22}" style="margin-top: 20px"
                               prop="capitalizedAmount">
              <a-input disabled v-model="computedCapitalizedAmount" placeholder="请输入金额大写"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="申请说明" :labelCol="{span:4}" :wrapperCol="{span:20}" prop="applicantReason">
              <a-textarea v-model="model.applicantReason" placeholder="请输入申请说明" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="合同条款" :labelCol="{span:4}" :wrapperCol="{span:20}" prop="contractTerms">
              <a-textarea v-model="model.contractTerms" placeholder="请输入合同条款" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="所获物资" :labelCol="{span:2}" :wrapperCol="{span:22}" prop="suppliesObtained">
              <a-textarea v-model="model.suppliesObtained" placeholder="请输入所获物资" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 添加合同预览模态框 -->
    <FundingApplicationContractPreviewModal ref="FundingApplicationContractPreviewModal" />
  </a-spin>
</template>

<script>

import { httpAction, getAction, putAction } from '@/api/manage'
import TslSelectUserSingle from '@comp/tsl/TslSelectUserSingle.vue'
import { getRefPromise } from '@comp/jeecg/JVxeTable/utils/vxeUtils'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import SelectProcurementModal from '@views/business/procurement/modules/SelectProcurementModal.vue'
import SelectOrderListModal from '@views/business/procurement/modules/SelectOrderListModal.vue'
import TslSelectFinanceUser from '@views/business/procurement/TslSelectFinanceUser.vue'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import JFormContainer from '@comp/jeecg/JFormContainer.vue'
import FundingApplicationContractPreviewModal from './FundingApplicationContractPreviewModal.vue';
import { JeecgListMixin } from '@/mixins/JeecgListMixin' // 确保路径正确


export default {
  name: 'FundingApplicationForm',
  mixins: [JVxeTableModelMixin,JeecgListMixin],
  components: {
    SelectOrderListModal,
    SelectProcurementModal,
    TslSelectUserSingle,
    TslSelectFinanceUser,
    JFormContainer,
    FundingApplicationContractPreviewModal, // 确保这里注册正确
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data() {
    return {
      refKeys: ['procurementContractReviewDetail'],
      activeKey: 'procurementContractReviewDetail',
      procurementContractReviewTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '合同审批单号',
            key: 'code',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '供应商名称',
            key: 'supplierName',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '采购合同名称',
            key: 'name',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '制单人',
            key: 'createBy_dictText',
            type: JVXETypes.normal,
            width: '150px'
          },

          {
            title: '制单部门',
            key: 'sysOrgCode',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '文件地址',
            key: 'filePath',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '制单日期',
            key: 'createTime',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '操作',
            key: 'actions',
            width: '150px',
            align: 'center',
            fixed: 'right',
            type: JVXETypes.slot,
            slotName: 'action'
          }
        ]
      },
      model: {
        fundingApplicationNum: '',
        procurementContractReviewIds: '',
        procurementCode: '',
        documentType: '',
        vendorName: '',
        procurementEnterprises: '特丝丽化工有限公司',
        procurementContractReviewDetail: [
          {
            id: '',
            code: '',
            supplierId: '',
            testId: '',
            filePath: '',
            createBy: '',
            sysOrgCode: '',
            createTime: '',
            remark: ''
          }
        ]
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        applicantAmount: [{ required: true, message: '请输入申请金额!'},{
          validator: (rule, value, callback) => {
            // 检查是否为数字
            if (isNaN(value) || value === '') {
              callback('请输入有效的数字');
              return;
            }
            // 转换为数字类型
            const numValue = parseFloat(value);
            // 检查是否为正数
            if (numValue <= 0) {
              callback('金额必须为正数');
              return;
            }
            // 检查小数位数（可选）
            const decimalCount = (value.toString().split('.')[1] || []).length;
            if (decimalCount > 2) {
              callback('最多保留两位小数');
              return;
            }
            callback();
          },
          trigger: ['blur', 'change'] // 触发校验的时机
        }],
      },
      url: {
        list:'/procurement/fundingApplication/list',
        add: '/procurement/fundingApplication/add',
        edit: '/procurement/fundingApplication/edit',
        queryById: '/procurement/fundingApplication/queryById',
        procurementContractReviewDetail: {
          list: '/procurement/fundingApplication/queryFundingProcurementById'
        }
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    updatedColumns() {
      // 如果需要动态调整列配置，可以通过 computed 返回
      return this.procurementContractReviewTable.columns
    },
    // 计算属性监听批准金额变化
    computedCapitalizedAmount: {
      get() {
        return this.model.applicantAmount ? this.convertToChinese(this.model.applicantAmount) : ''
      },
      set(val) {
        this.model.capitalizedAmount = val
      }
    }
  },
  watch: {
    // 监听计算属性变化并更新model
    computedCapitalizedAmount(newVal) {
      this.model.capitalizedAmount = newVal
    }
  },
  created() {
    // //备份model原始值
    // this.modelDefault = JSON.parse(JSON.stringify(this.model))
    //如果是审批流进来的时候要将审批流的数据显示出来
    console.log("this.model", this.model, this.customFormData);
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      this.procurementContractReviewTable.dataSource = this.customFormData.procurementContractReviewDetail;
    }
  },
  methods: {

    handleCallBack(str,res){
      console.log("11111111111111111111111111111",res)
        this.model.supplierId = res.supplierId
        this.model.vendorName = res.vendorName
    },
    //查看合同逻辑
    viewContract(row) {
      console.log("-----------------")
      console.log(row)
      // 假设 row 包含一个 filePath 属性，表示合同文件的路径
      if (row.filePath) {
        // 弹出查看合同的二级页面
        this.$refs.FundingApplicationContractPreviewModal.open(row.filePath);
      } else {
        this.$message.warning('该合同没有文件路径');
      }
    },

    handlePreviewFilePDF(rowpath) {
      let realPath = this.getImgView(rowpath)
      let base = window._CONFIG.onlinePreviewDomainURL + '/onlinePreview?url='
      let codename = Base64.encode(realPath)
      let url = base + codename + '&watermarkTxt=' + encodeURIComponent(store.getters.userInfo.username)
      return url
    },

    handleAmountChange(value) {
      // 实时处理金额变化（可选）
      if (value >= 0) {
        this.model.applicantAmount = value
      }
    },
    // 数字转中文大写金额
    convertToChinese(number) {
      if (!number && number !== 0) return ''
      const fraction = ['角', '分']
      const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      const unit = [
        ['元', '万', '亿'],
        ['', '拾', '佰', '仟']
      ]
      let num = Math.abs(number)
      let s = ''

      // 处理小数部分
      for (let i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(num * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
      }
      s = s || '整'
      num = Math.floor(num)

      // 处理整数部分
      for (let i = 0; i < unit[0].length && num > 0; i++) {
        let p = ''
        for (let j = 0; j < unit[1].length && num > 0; j++) {
          p = digit[num % 10] + unit[1][j] + p
          num = Math.floor(num / 10)
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
      }

      return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
    },
    addProducts() {
      this.$nextTick(() => {
        this.$refs.selectModal.add()
      })
    },
    handleDeleteRow(row) {
      getRefPromise(this, this.refKeys[0]).then(vxeTable => {
        vxeTable.removeRowsById(row.rowId)

        // 强制响应式更新
        this.model.procurementContractReviewDetail = vxeTable.getTableData()
        this.procurementContractReviewTable.dataSource = [...vxeTable.getTableData()]

        this.$message.success('删除成功')
      })
    },
    selProductsOk(rows) {
      if (rows && rows.length > 0) {
        rows.forEach((item) => {
          let detail = {
            code: item.code,
            supplierName: item.supplierName,
            supplierId:item.supplierId,
            name: item.name,
            filePath: item.filePath,
            createBy: item.createBy,
            sysOrgCode: item.sysOrgCode,
            createTime: item.createTime,
            remark: item.remark
          }
          this.procurementContractReviewTable.dataSource.push(detail)
        })
      }
    },
    handleChangeTabs(key) {
      getRefPromise(this, key).then(vxeTable => {
        vxeTable.resetScrollTop()
      })
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/funding_application_code'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.fundingApplicationNum = res.result
        }
      })
    },
    add(params) {
      this.getSequenceNum()
      console.log("123",params)
      if(params.length>0){
        console.log("1111111111111111111111")
        console.log(params.procurementCode)
        this.model.procurementCode = params.procurementCode, // 采购订单号
          this.model.documentType = params.documentType, // 单据类型
          this.model.vendorName = params.vendorName, // 供应商
          this.model.procurementEnterprises = params.procurementEnterprises // 采购企业
      }
      this.edit(this.model)
    },
    edit(record) {
      this.model = {
        ...this.modelDefault, // 保留初始值
        ...record // 覆盖为后端数据
      }
      this.editAfter()
    },

    // 假设这是你从后端API获取数据的函数
    requestSubTableData(url, params, table) {
      getAction(url, params).then(res => {
        if (res.success) {
          // 确保返回的数据中每个对象都有 filePath 属性
          console.log("-------"+res.result)
          res.result.forEach(item => {
            if (!item.filePath) {
              console.warn('文件路径缺失:', item);
            }
          });
          this.procurementContractReviewTable.dataSource = res.result;
          this.model.procurementContractReviewDetail = res.result; // 同步到 model
        }
      });
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      if (this.model.procurementContractReviewIds) {
        let params = { ids: this.model.procurementContractReviewIds}
        this.requestSubTableData(this.url.procurementContractReviewDetail.list, params, this.procurementContractReviewTable)
        //刷新明细的时候 还要将这个数据传输到要提交的表单中
        if (this.procurementContractReviewTable) {
          this.model.procurementContractReviewDetail = this.procurementContractReviewTable.dataSource
        }
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          getRefPromise(this, this.refKeys[0]).then(vxeTable => {
            this.model.procurementContractReviewDetail = vxeTable.getTableData()
          })
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              // if (!this.model.id) {
              //   this.model.dataId = res.message
              //   that.applySubmit(this.model)
              // }
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          var params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'fundingApplicationService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
    //防止提交多次
    handleOk() {
    },
    handleSelectUser1() {
      this.$refs.selectUserModal1.visible = true
    },
    selectOK(data) {
      this.$set(this.model, 'applyUserName', data.employeeName)  // 使用Vue的响应式更新
      this.$set(this.model, 'applicant', data.employeeCode)
    },
    handleSelectOrder() {
      this.$refs.selectOrderModal.visible = true
    },
    selectOKOrder(data) {
      if (data.code?.includes('YLCG')) {
        this.$set(this.model, 'documentType', '1')  // 使用Vue的响应式更新
        this.$set(this.model, 'procurementCode', data.code)
        this.$set(this.model, 'vendorName', data.supplierName)
        this.$set(this.model, 'procurementEnterprises', data.purchaseCompany)
        this.$set(this.model, 'supplierId', data.supplierId)
      } else if (data.code?.includes('WJCG')) {
        this.$set(this.model, 'documentType', '2')  // 使用Vue的响应式更新
        this.$set(this.model, 'procurementCode', data.code)
        this.$set(this.model, 'vendorName', data.supplierName)
        this.$set(this.model, 'procurementEnterprises', data.purchaseCompany)
        this.$set(this.model, 'supplierId', data.supplierId)
      } else if (data.code?.includes('BCCG')) {
        this.$set(this.model, 'documentType', '3')
        this.$set(this.model, 'procurementCode', data.code)
        this.$set(this.model, 'vendorName', data.supplierName)
        this.$set(this.model, 'procurementEnterprises', data.purchaseCompany)
        this.$set(this.model, 'supplierId', data.supplierId)
      } else if (data.code?.includes('CXCG')) {
        this.$set(this.model, 'documentType', '4')
        this.$set(this.model, 'procurementCode', data.code)
        this.$set(this.model, 'vendorName', data.supplierName)
        this.$set(this.model, 'procurementEnterprises', data.purchaseCompany)
        this.$set(this.model, 'supplierId', data.supplierId)
      }
    },
    handleSelectFinanceUser1() {
      this.$refs.selectUserModal2.visible = true
    },
    selectFinanceUserOK(data) {
      this.$set(this.model, 'financeUserName', data.employeeName)  // 使用Vue的响应式更新
      this.$set(this.model, 'financialInquirer', data.employeeCode)
    }
  }
}
</script>